package com.lzx.java.smack.concurrent;

import static org.junit.Assert.*;

import java.awt.MultipleGradientPaint.CycleMethod;
import java.util.Random;
import java.util.TreeMap;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Test;

public class CyclicBarrierTest {

	/**
	 * 假设有只有的一个场景：每个线程代表一个跑步运动员，当运动员都准备好后，才一起出发，<br>
	 * 只要有一个人没有准备好，大家都等待.
	 * 
	 * @throws InterruptedException
	 */
	@Test
	public void test1() throws InterruptedException {
		int size = 5;
		CyclicBarrier cyclicBarrier = new CyclicBarrier(size);

		ExecutorService executor = Executors.newFixedThreadPool(size);

		for (int i = 0; i < size; i++) {
			executor.execute(new Thread(new MyThread(cyclicBarrier)));
		}

		executor.shutdown();

		Thread.sleep(10000L);

	}
	
	@Test
	public void testTreeMap() {
		TreeMap<String, String> treeMap = new TreeMap<String, String>();
		treeMap.put("1", "1");
		treeMap.put("3", "3");
		treeMap.put("2", "2");
		System.out.println(treeMap);
		
	}

	private class MyThread implements Runnable {
		CyclicBarrier cyclicBarrier;

		public MyThread(CyclicBarrier cyclicBarrier) {
			this.cyclicBarrier = cyclicBarrier;
		}

		@Override
		public void run() {
			String name = Thread.currentThread().getName();
			try {

				Thread.sleep(1000 * (new Random()).nextInt(5));
				System.out
						.println(name + " 准备OK." + System.currentTimeMillis());
				cyclicBarrier.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
			System.out.println(name + " Go!!" + System.currentTimeMillis());

		}

	}

}
